<?php
/*****************************************************
* See fail on UTF-8 vormingus.
*
* Tiri algfailid siit:
* ftp://ftp.eki.ee/pub/keeletehnoloogia/inglise-eesti/et_en.current.wbt
* ftp://ftp.eki.ee/pub/keeletehnoloogia/inglise-eesti/en_et.current.wbt
*
* Enne baasi viimist kontrolli, kas failid on ikka UTF-8. Kui ei ole,
* lülita allpool sisse teisendus.
*
* EKI failis on vaikimisi ka 
******************************************************/

try {
	$dbh = new PDO("sqlite:nastik.db");
	$dbh->exec('DROP TABLE en_et');
	$dbh->exec('DROP TABLE et_en');
    $dbh->exec('CREATE TABLE en_et (id INTEGER PRIMARY KEY AUTOINCREMENT, word_en TEXT, word_et TEXT)');
    $dbh->exec('CREATE TABLE et_en (id INTEGER PRIMARY KEY AUTOINCREMENT, word_et TEXT, word_en TEXT)');

	// EN -> ET
	$filename = 'en_et.current.wbt';
	$handle = fopen ($filename, "r");
	$contents = fread ($handle, filesize ($filename));
	fclose ($handle);

	$arr = explode("\n", $contents);
	$kaunt = count($arr);

	$dbh->beginTransaction();
	for ($i=0; $i<$kaunt-1; $i++){		// $kaunt-1, sest vaikimisi on EKI failil tühi rida lõpus
		$rida = explode("\t", $arr[$i]);
		// kui algfail ei ole UTF-8, lülita teisendus sisse, EKI fail nt brauserist salvestades ei pruugi olla
		// $rida[0] = utf8_encode($rida[0]);
		// $rida[1] = utf8_encode($rida[1]);
		$cmd = $dbh->prepare("INSERT INTO en_et (word_en, word_et) VALUES (:en, :et)"); 
		$cmd->bindParam(':en', $rida[0]);
		$cmd->bindParam(':et', $rida[1]);
		$cmd->execute();
	}
	$dbh->commit();
	
	// ET -> EN
	$filename = 'et_en.current.wbt';
	$handle = fopen ($filename, "r");
	$contents = fread ($handle, filesize ($filename));
	fclose ($handle);

	$arr = explode("\n", $contents);
	$kaunt = count($arr);

	$dbh->beginTransaction();
	for ($i=0; $i<$kaunt-1; $i++){		// $kaunt-1, sest vaikimisi on EKI failil tühi rida lõpus
		$rida = explode("\t", $arr[$i]);
		// kui algfail ei ole UTF-8, lülita teisendus sisse, EKI fail nt brauserist salvestades ei pruugi olla
		// $rida[0] = utf8_encode($rida[0]);
		// $rida[1] = utf8_encode($rida[1]);
		$cmd = $dbh->prepare("INSERT INTO et_en (word_et, word_en) VALUES (:et, :en)"); 
		$cmd->bindParam(':et', $rida[0]);
		$cmd->bindParam(':en', $rida[1]);
		$cmd->execute();
	}
	$dbh->commit();

    $dbh = null;
}
catch(PDOException $e)
	{
	echo $e->getMessage();
	}
?>
